<?php

namespace app\controllers;

use app\models\Account;
use app\models\AidForm;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use yii\web\Response;
use yii\helpers\Json;

class SiteController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action)
    {
        $this->enableCsrfValidation = false;
        return parent::beforeAction($action);
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionLogin()
    {
//        //测试数据库功能：
//        $account = Account::findByNumber('123456789');
//        Yii::info("------------------------------".$account->number.$account->money,__METHOD__);
//        Yii::info("actionLogin--------------",__METHOD__);
        $userAgentStr = Yii::$app->getRequest()->getUserAgent();
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            if ($userAgentStr === "HCE_Android_IOS_APP") {
                Yii::info('login OK request from iOS or Android Native App ua=' . $userAgentStr, __METHOD__);
                $this->_buildNativeAppResponse($model);
                Yii::$app->getResponse()->send();
            }
            return $this->goBack();
        }else {
            Yii::info("fail to load data ",__METHOD__);
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    public function actionAid(){
        $model = new AidForm();
        $userAgentStr = Yii::$app->request->getUserAgent();
        if($model->load(Yii::$app->request->post())){
            if($userAgentStr == "HCE_Android_IOS_APP"){
                $this->_buildNativeAppResponseAid($model);
                Yii::$app->getResponse()->send();
            }
        }
    }

    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    public function actionAbout()
    {
        return $this->render('about');
    }

    private function _buildNativeAppResponse($model)
    {
        if (!is_null($model) && !is_null($model->getUser())) {
            Yii::$app->getResponse()->setStatusCode(200);
            Yii::$app->getResponse()->format = Response::FORMAT_JSON;
            //$uid = sprintf(ILBConfig::UID_FORMAT, $model->getUser()->uid);
            $jsonStr = json_encode(['uid' => "0001", 'username' => $model->username]);
            $len = strlen(Json::encode($jsonStr));
            Yii::$app->getResponse()->getHeaders()->set('Content-Length', $len);
            Yii::$app->getResponse()->data = $jsonStr;
        }
    }

    private function _buildNativeAppResponseAid($model){
        if(!is_null($model)){
            Yii::$app->getResponse()->setStatusCode(200);
            Yii::$app->getResponse()->format = Response::FORMAT_JSON;
            $jsonStr = json_encode(Json::encode(['response'=>"6F438408A000000333010101A537500A50424F432044454249548701019F38189F66049F02069F03069F1A0295055F2A029A039C019F37045F2D027A68BF0C059F4D020B0A9000"]));
            $len = strlen(Json::encode($jsonStr));
            Yii::$app->getResponse()->getHeaders()->set('Content-Length', $len);
            Yii::$app->getResponse()->data = $jsonStr;
        }
    }
}
